package com.ikas.ai.utils;

import org.dom4j.Document;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;

import java.io.File;
import java.io.StringReader;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

/**
 * 条件过滤常用类
 * @author admin
 */
public class FilterUtil {
    private String whereSql;
    private String sortSql;
    private Map<String, Column> mapColumns = new LinkedHashMap<String, Column>();
    private Map<String, String> mapOp = new LinkedHashMap<String, String>();
    private Map<String, String> mapAo = new LinkedHashMap<String, String>();

    public FilterUtil(String path, String xml) throws Exception {
        mapOp.put("等于", "=");
        mapOp.put("不等于", "<>");
        mapOp.put("包含", "like");
        mapOp.put("左包含", "llike");
        mapOp.put("右包含", "rlike");
        mapOp.put("大于", ">");
        mapOp.put("小于", "<");
        mapOp.put("不大于", "<=");
        mapOp.put("不小于", ">=");

        mapAo.put("与", "and");
        mapAo.put("或", "or");

        // 加载定义文件，获得列名和id的对应关系
        String fileName = String.format("%sfiles/filter/filter.xml", path);
        File dFile = new File(fileName);
        if (dFile.exists()) {
            SAXReader reader = new SAXReader();
            Document doc = reader.read(fileName);
            List<?> nodes = doc.selectNodes("/filter/column/item");
            for (Object object : nodes) {
                Element node = (Element) object;
                String id = attVal(node, "id");
                String name = attVal(node, "name");
                String dataType = attVal(node, "datatype");
                Column column = new Column(id, name, dataType);
                // logger.debug(String.format("%s - %s", id, name));
                mapColumns.put(name, column);
            }
        }
        // 读取过滤条件，组合SQL
        StringBuffer sb = new StringBuffer();
        StringReader reader = new StringReader(xml);
        SAXReader sr = new SAXReader();
        Document schemedoc = sr.read(reader);
        List<?> schemenodes = schemedoc.selectNodes("/scheme/where/item");
        // logger.debug(schemenodes.size());
        for (Object object : schemenodes) {
            Element node = (Element) object;
            String lb = attVal(node, "lb");
            String col = attVal(node, "col");
            String colname = mapColumns.get(col).getId();
            String dt = mapColumns.get(col).getDataType();
            String op = mapOp.get(attVal(node, "op"));
            String val = attVal(node, "val");
            String rb = attVal(node, "rb");
            String ao = mapAo.get(attVal(node, "ao"));
            if (!"".equals(col) && !"".equals(op)) {
                String opval = "";
                if ("like".equals(op)) {
                    opval = "like \'%" + val + "%\'";
                } else if ("llike".equals(op)) {
                    opval = "like \'" + val + "%\'";
                } else if ("rlike".equals(op)) {
                    opval = "like \'%" + val + "\'";
                } else if ("string".equals(dt) || "date".equals(dt)) {
                    opval = op + " \'" + val + "\'";
                } else {
                    opval = op + " " + val + "";
                }
                sb.append(String.format("%s%s %s%s %s ", lb, colname, opval, rb, ao == null ? "" : ao));
            }
        }
        this.whereSql = new String(sb.toString().getBytes("GBK"), "ISO-8859-1");
        if (this.whereSql.endsWith("and ")) {
            this.whereSql = this.whereSql.substring(0, this.whereSql.length() - 5);
        }
        if (this.whereSql.endsWith("or ")) {
            this.whereSql = this.whereSql.substring(0, this.whereSql.length() - 4);
        }
        // logger.debug(this.whereSql);
    }

    private String attVal(Element node, String attName) {
        String val = node.attributeValue(attName);
        return val == null ? "" : val.trim();
    }

    public String getWhereSql() {
        return whereSql;
    }

    public void setWhereSql(String whereSql) {
        this.whereSql = whereSql;
    }

    public String getSortSql() {
        return sortSql;
    }

    public void setSortSql(String sortSql) {
        this.sortSql = sortSql;
    }

    /**
     * 数据表列对像
     * @author admin
     */
    public class Column {
        private String id;
        private String name;
        private String dataType;

        public Column(String id, String name, String dataType) {
            this.id = id;
            this.name = name;
            this.dataType = dataType;
        }

        public void setId(String id) {
            this.id = id;
        }

        public String getId() {
            return id;
        }

        public void setName(String name) {
            this.name = name;
        }

        public String getName() {
            return name;
        }

        public String getDataType() {
            return dataType;
        }

        public void setDataType(String dataType) {
            this.dataType = dataType;
        }
    }
}
